import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import storage from "./storage";
import { config } from "@/config/env.config";

const TOKEN_INVALID = 'Token认证失败,请重新登录'
const NETWORK_ERROR = '网络异常,请稍后再试'

// 创建专门用于JWT验证的axios实例
export const jwtRequest = axios.create({
    baseURL: config.baseApi,
    timeout: 8000,
})

// 请求拦截器
jwtRequest.interceptors.request.use((config) => {
    // 从localStorage获取token
    const token = storage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config;
}, (error) => {
    return Promise.reject(error);
})

// 响应拦截器
jwtRequest.interceptors.response.use((response) => {
    const { code, data, msg } = response.data
    if (code === 200) {
        return response.data
    } else if (code === 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            storage.clearItem('token')
            router.push('/login')
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }
}, (error) => {
    if (error.response?.status === 401) {
        storage.clearItem('token')
        router.push('/login')
    }
    return Promise.reject(error)
}) 